Imports System.IO
Imports System.Text


Public Class CExel
    Public Shared Sub ExpDGVtoExcell(ByVal f_grid As DataGridView)
        Dim s_StrW As Stream
        Dim s_StrWriter As StreamWriter
        Dim i_rows = f_grid.Rows.Count
        Dim i_cols = f_grid.Columns.Count
        Dim f_libro As String = Application.StartupPath & "\Libro_datagridview.csv"
        Dim s_fila As String = ""
        Dim r As Integer
        Dim c As Integer

        File.Delete(f_libro)
        s_StrW = File.OpenWrite(f_libro)

        s_StrWriter = New StreamWriter(s_StrW, System.Text.Encoding.UTF8)

        'Aqui se asignan los encabezados
        For c = 0 To i_cols - 1
            s_fila = s_fila & f_grid.Columns(c).HeaderText & " , "
        Next

        s_fila = Mid(s_fila, 1, s_fila.ToString.Length - 1)
        s_StrWriter.WriteLine(s_fila)
        s_fila = Nothing

        'Aqui las filas
        For r = 0 To i_rows - 1
            For c = 0 To i_cols - 1
                s_fila = s_fila & f_grid.Item(c, r).Value & " , "
            Next
            s_fila = Mid(s_fila, 1, s_fila.ToString.Length - 1)
            s_StrWriter.WriteLine(s_fila)
            s_fila = Nothing
        Next
        s_StrWriter.Close()

        Try
            'Aqui habrimos el libro
            Process.Start(f_libro)
        Catch Ex As Exception
            MsgBox(Ex.Message, MsgBoxStyle.Critical, Ex.Source)
        End Try

    End Sub


End Class
